package com.tju.resource.server.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tju.resource.common.ServiceException;
import com.tju.resource.mapper.TbMaterialMapper;
import com.tju.resource.mapper.TbOrderMapper;
import com.tju.resource.mapper.TbRawMatlMapper;
import com.tju.resource.mapper.TbRmMatlMapper;
import com.tju.resource.model.SysRole;
import com.tju.resource.model.TbMaterial;
import com.tju.resource.model.TbRmMatl;
import com.tju.resource.server.TbMaterialService;
import com.tju.resource.server.TbProdPlanService;
import com.tju.resource.tool.result.Result;
import com.tju.resource.tool.result.ResultEnum;
import com.tju.resource.tool.result.ResultUtil;
import com.tju.resource.tool.tool.ClientParameters;
import com.tju.resource.tool.tool.EmptyUtils;
import com.tju.resource.tool.tool.QuickQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

import static com.tju.resource.tool.tool.QuickQuery.*;

/**
 *
 */
@Service
public class TbMaterialServiceImpl implements TbMaterialService {

    @Autowired
    TbMaterialMapper mapper;
    @Autowired
    private TbProdPlanService pService;
    @Autowired
    private TbOrderMapper tbOrderMapper;
    @Autowired
    private TbRmMatlMapper tbRmMatlMapper;
    @Autowired
    private TbRawMatlMapper tbRawMatlMapper;

    @Override
    public Result<Object> getAll(Map<String, String> params) {
        try {
            Page<TbMaterial> page = new Page<>(Long.parseLong(params.get("page")), Long.parseLong(params.get("limit")));
            IPage<TbMaterial> iPage = mapper.getAll(page, params);
            List<TbMaterial> records = iPage.getRecords();
            for (TbMaterial record : records) {
                record.setRmMatlList(mapper.selectTbRmMatl(record.getId()));
            }
            return ResultUtil.success(ResultEnum.SUCCESS, records, iPage.getTotal());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public Result<Object> byName(Map<String, String> params) {
        try {
            Page<TbMaterial> page = new Page<>(Long.parseLong(params.get("page")), Long.parseLong(params.get("limit")));
            IPage<TbMaterial> iPage = mapper.getAll(page, params);
            List<TbMaterial> records = iPage.getRecords();
            for (TbMaterial record : records) {
                record.setRmMatlList(mapper.selectTbRmMatl(record.getId()));
            }
            return ResultUtil.success(ResultEnum.SUCCESS, records, iPage.getTotal());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 根据订单查询物料 模具
     *
     * @param orderNumber
     * @return
     */
    @Override
    public Result<Object> byOrderNumber(Map<String, String> params) {
        if (EmptyUtils.isNotEmpty(params.get("orderNumber"))) {
            Page<TbMaterial> page = new Page<>(Long.parseLong(params.get("page")), Long.parseLong(params.get("limit")));
            IPage<TbMaterial> iPage = mapper.byOrderNumber(page, params);
            List<TbMaterial> records = iPage.getRecords();
            for (TbMaterial record : records) {
                record.setRmMatlList(mapper.selectTbRmMatl(record.getId()));
            }
            return ResultUtil.success(ResultEnum.SUCCESS, iPage.getRecords(), iPage.getTotal());
        } else {
            return ResultUtil.error(ResultEnum.UNKONW_ERROR, "订单号不能为空!");
        }
    }

    @Override
    public Result<Object> byOrderMatlNumber(Map<String, String> pa) {
        try {
            if (EmptyUtils.isNotEmpty(pa.get("orderNumber")) && EmptyUtils.isNotEmpty(pa.get("matlNumber"))) {
                TbMaterial material = mapper.byOrderMatlNumber(pa);
                if (EmptyUtils.isNotEmpty(material)) {
                    return ResultUtil.success(ResultEnum.SUCCESS);
                } else {
                    return ResultUtil.error(ResultEnum.UNKONW_ERROR);
                }
            } else {
                return ResultUtil.error(ResultEnum.UNKONW_ERROR, "订单不能为空");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResultUtil.error(ResultEnum.UNKONW_ERROR);
    }

    @Override
    public TbMaterial byId(Long matlId) {
        return mapper.selectById(matlId);
    }

    @Override
    public TbMaterial byNo(String matlNumber) {
        return byOne(mapper, "matl_number", matlNumber);
    }

    @Override
    public TbMaterial byNa(String matlName) {
        return byOne(mapper, "matl_name", matlName);
    }

    @Override
    @Transactional
    public Result<Object> add(TbMaterial material) {
        if (mapper.insert(material) > 0) {
            insetTbRmMatl(material); //添加物料跟原材料关联表
            return ResultUtil.success(ResultEnum.SUCCESS, "新增物料完成!");
        }
        return ResultUtil.error(ResultEnum.UNKONW_ERROR, "新增失败!");
    }

    @Override
    @Transactional
    public int upd(TbMaterial material) {
        int result = mapper.updateById(material);
        if (result > 0) {
            deleteTbRmMatl(material.getId());//删除原材料
            insetTbRmMatl(material); //添加物料跟原材料关联表
        }
        return result;
    }

    @Override
    public int del(Long matlId) {
        if (EmptyUtils.isNotEmpty(tbOrderMapper.getListOrder(matlId)) || EmptyUtils.isNotEmpty(pService.getByMatlId(matlId))) {
            throw new ServiceException("该物料被使用了不能删除");
        }
        deleteTbRmMatl(matlId);//删除原材料
        return mapper.deleteById(matlId);
    }

    /**
     * 删除物料跟原材料关联表
     *
     * @param id 删除物料的id
     */
    private void deleteTbRmMatl(Long id) {
        QueryWrapper<TbRmMatl> qw = new QueryWrapper<>();
        qw.eq("matl_id", id);
        tbRmMatlMapper.selectList(qw).forEach(t -> tbRmMatlMapper.deleteById(t.getId())); //删除原材料
    }

    /**
     * 添加原材料关联表
     *
     * @param material //物料
     */
    private void insetTbRmMatl(TbMaterial material) {
        if (EmptyUtils.isNotEmpty(material.getRmMatlList())) {
            for (TbRmMatl rmMatl : material.getRmMatlList()) {
                if (EmptyUtils.isNotEmpty(rmMatl.getRawMatl())) {  //判断不为空就用这个id
                    rmMatl.setId(rmMatl.getRawMatl().getId());
                }
                if (EmptyUtils.isEmpty(tbRawMatlMapper.selectById(rmMatl.getId())))
                    throw new ServiceException("该原物料不存在!");
                if (EmptyUtils.isEmpty(rmMatl.getRmRadio()) || rmMatl.getRmRadio() == 0)
                    throw new ServiceException("消耗数量不能为空和为0!");
                rmMatl.setRmId(rmMatl.getId());
                rmMatl.setMatlId(material.getId());
                rmMatl.setId(null);
                tbRmMatlMapper.insert(rmMatl);
            }
        } else {
            throw new ServiceException("未选择原材料!");
        }
    }
}
